package microservicedemo.userservice.controller;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import microservicedemo.userservice.mapper.UserMapper;
import microservicedemo.userservice.po.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@AllArgsConstructor
@RestController
@Slf4j
public class UserController {
    private final UserMapper userMapper;

    @PostMapping("/login")
    public String  login(@RequestBody User user) {
        Integer id = userMapper.login(user);
        String signKey = "micro";
        log.info("-------------OK   /login--------------------");
        log.info("id:{}", id);
        Map<String,Object> claims = new HashMap<>();
        claims.put("username",user.getUsername());
        if(id != null){
            try {
                long expire = 43200000L;

                return Jwts.builder()
                        .addClaims(claims)
                        .signWith(SignatureAlgorithm.HS256, signKey)
                        .setExpiration(new Date(System.currentTimeMillis() + expire))
                        .compact();

            } catch (Exception e) {
                return null;
            }
        }else {
            return "用户不存在或密码错误，无法登录";
        }
    }

    @PostMapping("/register")
    public boolean register(@RequestBody User user) {
        userMapper.register(user);
        return true;
    }
}
